package com.kaiwukj.android.ufamily.mvp.ui.page.mine.house.door;

import android.util.SparseBooleanArray;
import android.widget.CheckBox;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DoorAccessDeviceResult;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class DoorAccessListAdapter extends BaseQuickAdapter<DoorAccessDeviceResult.UnitListBean, BaseViewHolder> {

    private SparseBooleanArray sparseBooleanArray;

    private int type;
    private int lastPosition = -1;

    public DoorAccessListAdapter(int type) {
        this(new ArrayList<>(), type);
    }

    public DoorAccessListAdapter(List<DoorAccessDeviceResult.UnitListBean> data, int type) {
        super(R.layout.item_door_access_list, data);
        sparseBooleanArray = new SparseBooleanArray();
        this.type = type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void check(int position) {
        if (position == lastPosition) return;
        if (lastPosition != -1) {
            sparseBooleanArray.put(lastPosition, false);
            notifyItemChanged(lastPosition);
        }
        lastPosition = position;
        sparseBooleanArray.put(lastPosition, true);
        notifyItemChanged(lastPosition);
    }

    public DoorAccessDeviceResult.UnitListBean getChecked() {
        return lastPosition == -1 ? null : getItem(lastPosition);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, DoorAccessDeviceResult.UnitListBean item) {
        LogUtils.d("type------------------------->" + type);
        LogUtils.d("item------------------------->" + GsonUtils.toJson(item));
        TextView tvName = holder.getView(R.id.tv_access_name);
        if (type == 3) {
            tvName.setText(item.getRoomName());
        } else {
            tvName.setText(item.getName());
        }
        CheckBox cb = holder.getView(R.id.cb_check);
        cb.setChecked(sparseBooleanArray.get(holder.getAdapterPosition()));
        holder.itemView.setOnClickListener(v -> check(holder.getAdapterPosition()));
    }
}
